package com.huitone.gddw.controller.business;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huitone.gddw.annotation.RequestLimit;
import com.huitone.gddw.common.excel.CreateExcel;
import com.huitone.gddw.controller.common.CommonController;
import com.huitone.gddw.dao.entity.SendSm;
import com.huitone.gddw.dao.entity.SmLog;
import com.huitone.gddw.dao.entity.SvrNodeDef;
import com.huitone.gddw.log.Log;
import com.huitone.gddw.log.LogResult;
import com.huitone.gddw.log.LogType;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.business.ISendSmService;
import com.huitone.gddw.service.dto.SvrNodeDefDTO;
import com.huitone.gddw.service.dto.analysis.SmSubmitFailDetailDTO;
import com.huitone.gddw.service.dto.business.RecvSmDTO;
import com.huitone.gddw.service.dto.business.SendSmCountDTO;
import com.huitone.gddw.service.dto.business.SendSmDTO;
import com.huitone.gddw.utils.SysLoginUtil;

/**
 * 短信发送记录 控制器
 * @author wuluodan
 *
 */
@Controller
@RequestMapping(value="sendSm")
public class SendSmController extends CommonController {

	private final static Logger LOGGER = Logger.getLogger(SendSmController.class);
	
	@Autowired
	private ISendSmService sendSmService;
	
	/**
	 * 查询
	 * @param page
	 * @param request
	 * @return QueryPage
	 */
	@ResponseBody
	@RequestMapping(value="query")
	@Log(logType=LogType.SELECT, content="查询短信发送明细")
	public QueryPage<SendSmDTO> query(QueryPage<SendSm> page, HttpServletRequest request) {
		QueryPage<SendSmDTO> result = null;
		try {
			page.setParams(getParams(request));
			result = sendSmService.selectPage(page);
		} catch (Exception e) {
			LOGGER.error("查询短信发送明细出现异常：" + e.getMessage(), e);
			request.setAttribute("logResult", LogResult.EXCEPTION);
		}
		return result;
	}
	
	
	
	@ResponseBody
	@RequestMapping(value="sendMsg",method=RequestMethod.GET)
	@RequestLimit(time=60000,count=10)
	@Log(logType=LogType.SELECT, content="短信发送查询")
	public Map<String, Object> querySendMsg(HttpServletRequest request) {
		Map<String, Object> result = null;
		try {
			result = sendSmService.querySendMsgPage(getParams(request));
		} catch (Exception e) {
			LOGGER.error("查询短信发送明细出现异常：" + e.getMessage(), e);
			request.setAttribute("logResult", LogResult.EXCEPTION);
		}
		return result;
	}
	
	
	
	@ResponseBody
	@RequestMapping(value="smSendByKey",method=RequestMethod.GET)
	@RequestLimit(time=60000,count=10)
	@Log(logType=LogType.SELECT, content="关键字查询短信发送")
	public Map<String, Object> queryByKeyword(HttpServletRequest request) {
		Map<String, Object> result = null;
		try {
			
			result = sendSmService.selectPageByKeyword(getParams(request));
		} catch (Exception e) {
			LOGGER.error("关键字查询短信发送出现异常：" + e.getMessage(), e);
			request.setAttribute("logResult", LogResult.EXCEPTION);
		}
		return result;
	}
	
	
	
	/**
	 * 获取参数信息
	 * @param request
	 * @return Map<String, Object>
	 */
	private Map<String, Object> getParams(HttpServletRequest request) {
		String svrNode = request.getParameter("svrNode");
		String serviceCode = request.getParameter("serviceCode");
		String userNo = request.getParameter("userNo");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		
		String total = request.getParameter("total");
		String sendSuc = request.getParameter("sendSuc");
		String sendFail = request.getParameter("sendFail");
		String recvSuc = request.getParameter("recvSuc");
		String recvFail = request.getParameter("recvFail");
		String recvNone = request.getParameter("recvNone");
		String upTotal = request.getParameter("upTotal");
		
		String smSeq = request.getParameter("smSeq");
		String limitCount = request.getParameter("limitCount");
		
		String sendCode = request.getParameter("sendCode");
		String resultCode = request.getParameter("resultCode");
		
		String svrNodes = request.getParameter("svrNodes");
		String preDateInfo = request.getParameter("preDateInfo");
		
		
		//新接口需要
		String pageIndex = request.getParameter("pageIndex");
		String pageSize = request.getParameter("pageSize");
		String key = request.getParameter("key");
		String account = request.getParameter("account");
		String receivePhone = request.getParameter("receivePhone");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("svrNode", svrNode);
		params.put("serviceCode", serviceCode);
		params.put("userNo", userNo);
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		params.put("total", total);
		params.put("sendSuc", sendSuc);
		params.put("sendFail", sendFail);
		params.put("recvSuc", recvSuc);
		params.put("recvFail", recvFail);
		params.put("recvNone", recvNone);
		params.put("upTotal", upTotal);	
		params.put("smSeq", smSeq);
		params.put("limitCount", limitCount);
		params.put("sendCode", sendCode);
		params.put("resultCode", resultCode);
		params.put("svrNodes", svrNodes);
		params.put("preDateInfo", preDateInfo);
		
		
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);
		params.put("key", key);
		params.put("account", account);
		params.put("receivePhone", receivePhone);
		params.put("startTime", startTime);
		params.put("endTime", endTime);
		
		return params;
	}
	
	/**
	 * 详情
	 * @param recId 记录ID
	 * @return SendSmDTO
	 */
	@ResponseBody
	@RequestMapping(value="detail")
	public SendSmDTO detail(String recId) {
		try {
			return sendSmService.getDetial(recId);
		} catch (Exception e) {
			LOGGER.error("查询短信发送明细详情出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	
	
	//--------------------------------------------

	

	@ResponseBody
	@RequestMapping(value="queryMMCount")
	public List queryMMCount(QueryPage<SendSmCountDTO> qp,HttpServletRequest request) {
		try {
			Map<String, Object> map = getParams(request);
			map.put("dateType", "mm");
			List<SendSmCountDTO> list = sendSmService.getCountByTimeType(map);
			qp.setParams(map);
			return sendSmService.dealList(list, qp);
		} catch (Exception e) {
			LOGGER.error("查询发送时间统计详情出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	@ResponseBody
	@RequestMapping(value="queryDDCount")
	public List queryDDCount(QueryPage<SendSmCountDTO> qp,HttpServletRequest request) {
		
		try {
			Map<String, Object> map = getParams(request);
			map.put("dateType", "dd");
			List<SendSmCountDTO> list = sendSmService.getCountByTimeType(map);
			qp.setParams(map);
			return sendSmService.dealList(list, qp);
		} catch (Exception e) {
			LOGGER.error("查询发送时间统计详情出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	
	@ResponseBody
	@RequestMapping(value="queryHHCount")
	public List queryHHCount(QueryPage<SendSmCountDTO> qp,HttpServletRequest request) {
		
		try {
			Map<String, Object> map = getParams(request);
			map.put("dateType", "hh24");
			List<SendSmCountDTO> list = sendSmService.getCountByTimeType(map);
			qp.setParams(map);
			return sendSmService.dealList(list, qp);
		} catch (Exception e) {
			LOGGER.error("查询发送时间统计详情出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	@ResponseBody
	@RequestMapping(value="queryMICount")
	public List queryMICount(QueryPage<SendSmCountDTO> qp,HttpServletRequest request) {
		
		try {
			Map<String, Object> map = getParams(request);
			map.put("dateType", "mi");
			List<SendSmCountDTO> list = sendSmService.getCountByTimeType(map);
			qp.setParams(map);
			return sendSmService.dealList(list, qp);
		} catch (Exception e) {
			LOGGER.error("查询发送时间统计详情出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	//------------------------------
	
	/**
	 * 导出 Excel
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/out-excel-mm",method=RequestMethod.POST)
	public void outMMExcel(HttpServletRequest request, HttpServletResponse response) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "短信月维度统计明细表";
		
		Map<String, Object> params = new HashMap<String, Object>();
		for (Object name : request.getParameterMap().keySet()) {
			params.put(name.toString(), request.getParameter(name.toString()));
		}
		params.put("dateType", "mm");
		List<SendSmCountDTO> list = (List<SendSmCountDTO>) sendSmService.getCountByTimeType(params);
		
		if (null == list) {
			list=new ArrayList<>();
			list.add(new SendSmCountDTO());
		}
		if (0 == list.size()) {
			list.add(new SendSmCountDTO());
		}
		
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, list).getWorkbook();
		OutputStream fOut = null;
		try {
			fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename="+fileName+sdf.format(new Date())+".xls");
			fOut = response.getOutputStream();
			wb.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}
	
	/**
	 * 导出 Excel
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/out-excel-dd",method=RequestMethod.POST)
	public void outDDExcel(HttpServletRequest request, HttpServletResponse response) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "短信日维度统计明细表";
		
		Map<String, Object> params = new HashMap<String, Object>();
		for (Object name : request.getParameterMap().keySet()) {
			params.put(name.toString(), request.getParameter(name.toString()));
		}
		params.put("dateType", "dd");
		List<SendSmCountDTO> list = (List<SendSmCountDTO>) sendSmService.getCountByTimeType(params);
	
		if (null == list) {
			list=new ArrayList<>();
			list.add(new SendSmCountDTO());
		}
		if (0 == list.size()) {
			list.add(new SendSmCountDTO());
		}
		
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, list).getWorkbook();
		OutputStream fOut = null;
		try {
			fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename="+fileName+sdf.format(new Date())+".xls");
			fOut = response.getOutputStream();
			wb.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}
	/**
	 * 导出 Excel
	 * @param request
	 * @param responsef
	 */
	@RequestMapping(value="/out-excel-hh24",method=RequestMethod.POST)
	public void outHHExcel(HttpServletRequest request, HttpServletResponse response) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "短信时维度统计明细表";
		
		Map<String, Object> params = new HashMap<String, Object>();
		for (Object name : request.getParameterMap().keySet()) {
			params.put(name.toString(), request.getParameter(name.toString()));
		}
		params.put("dateType", "hh24");
		List<SendSmCountDTO> list = (List<SendSmCountDTO>) sendSmService.getCountByTimeType(params);
	
		if (null == list) {
			list=new ArrayList<>();
			list.add(new SendSmCountDTO());
		}
		if (0 == list.size()) {
			list.add(new SendSmCountDTO());
		}
		
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, list).getWorkbook();
		OutputStream fOut = null;
		try {
			fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename="+fileName+sdf.format(new Date())+".xls");
			fOut = response.getOutputStream();
			wb.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}
	/**
	 * 导出 Excel
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/out-excel-mi",method=RequestMethod.POST)
	public void outMIExcel(HttpServletRequest request, HttpServletResponse response) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "短信分维度统计明细表";
		
		Map<String, Object> params = new HashMap<String, Object>();
		for (Object name : request.getParameterMap().keySet()) {
			params.put(name.toString(), request.getParameter(name.toString()));
		}
		params.put("dateType", "mi");
		List<SendSmCountDTO> list = (List<SendSmCountDTO>) sendSmService.getCountByTimeType(params);
		
		if (null == list) {
			list=new ArrayList<>();
			list.add(new SendSmCountDTO());
		}
		if (0 == list.size()) {
			list.add(new SendSmCountDTO());
		}
		
		
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, list).getWorkbook();
		OutputStream fOut = null;
		try {
			fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename="+fileName+sdf.format(new Date())+".xls");
			fOut = response.getOutputStream();
			wb.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}
	//短信发送查询页面导出excel
	@RequestMapping(value="/out-excel", method=RequestMethod.POST)
	public void outExcel(HttpServletRequest request, HttpServletResponse response) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "短信发送明细表";
		
		Map<String, Object> params = new HashMap<String, Object>();
		for (Object name : request.getParameterMap().keySet()) {
			params.put(name.toString(), request.getParameter(name.toString()));
		}
		
		List<SendSmDTO> list = sendSmService.getRecord(params);
		if (null == list || 0 == list.size()) {
			list.add(new SendSmDTO());
		}
		
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, list).getWorkbook();
		OutputStream fOut = null;
		try {
			fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename="+fileName+sdf.format(new Date())+".xls");
			fOut = response.getOutputStream();
			wb.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}
}
